package com.yumeng.common.data.validator;

import com.yumeng.common.data.enums.BaseEnum;
import com.yumeng.common.exception.YumengException;
import com.yumeng.common.data.validator.annotation.EnumType;
import com.yumeng.common.helper.BaseEnumHelper;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * 自定义系统内部枚举验证注解
 * @author wxd
 * @date 2021/2/1 17:24
 */
public class EnumTypeValidator implements ConstraintValidator<EnumType, Integer> {

    private Class<? extends BaseEnum> baseEnum;

    @Override
    public void initialize(EnumType constraintAnnotation) {
        baseEnum = constraintAnnotation.type();
        if (baseEnum == null) {
            throw new YumengException("请传入枚举类型类");
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return BaseEnumHelper.exists(baseEnum, value);
    }
}
